package com.kplzj.maptest.map.customView;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;

import com.kplzj.maptest.map.CarPathView;

import java.util.ArrayList;
import java.util.List;

/**
 * 原生地图绘制
 */
public class CustomAreaMapView extends View {
    private List<Path> paths;
    private Paint paint;
    private Matrix matrix; // 用于应用平移和缩放变换
    private float scaleFactor = 5f; // 地图和小车默认缩放的倍数
    private float scaleFactorCar = 3.0f; // 地图和小车进入项目之后再次放大的倍数
    private float translateX = 0f; // X轴平移量
    private float translateY = 0f; // Y轴平移量

    List<Float> minXYList;
    List<String> colorList;

    private float pivotX = 0; // 放大中心点 X 坐标
    private float pivotY = 0; // 放大中心点 Y 坐标

    /**
     * 小车
     * @param context
     */
    private List<PointF> points; // 存储点的列表


    public CustomAreaMapView(Context context) {
        super(context);
        init(context);
    }

    public CustomAreaMapView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CustomAreaMapView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {

        matrix = new Matrix();
        paint = new Paint();
        paint.setAlpha(64);

//        gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
//            @Override
//            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
//                translateX -= distanceX;
//                translateY -= distanceY;
//                invalidate();
//                return true;
//            }
//
//            @Override
//            public boolean onDoubleTap(MotionEvent e) {
//                scaleFactor *= 2; // 或者可以设置为其他缩放逻辑
//                scaleFactorCar *= 2;
//                invalidate();
//                return true;
//            }
//        });
//
//        scaleGestureDetector = new ScaleGestureDetector(context, new ScaleGestureDetector.SimpleOnScaleGestureListener() {
//            @Override
//            public boolean onScale(ScaleGestureDetector detector) {
//                scaleFactor *= detector.getScaleFactor();
//                scaleFactorCar *= detector.getScaleFactor();
//                invalidate();
//                return true;
//            }
//        });
    }

    // 在这里处理触摸事件
//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        gestureDetector.onTouchEvent(event);
//        scaleGestureDetector.onTouchEvent(event);
//        return true; // 表示事件被处理
//    }

    //地图数据传入
    public void setPaths(XmlDataParser xmlDataParser,List<CarBean> carBeans) {

        pivotX = 0;
        pivotY = 0;
        paths = new ArrayList<>();
        points = new ArrayList<>();
        this.minXYList = xmlDataParser.getFloatList(); // 假设这是一个包含两个值的列表，分别为最小的 X 和 Y 坐标
        this.colorList = xmlDataParser.getSubAreaColor();

        List<MapBean> mapBeanList = xmlDataParser.getMapBeanList();
        for (MapBean mapBean : mapBeanList) {
            List<MapBean.SubAreasbean> subAreasList = mapBean.getSubAreas();
            for (int j = 0; j < subAreasList.size(); j++) {
                MapBean.SubAreasbean subArea = subAreasList.get(j);

                // 只处理偶数索引的子区域
                if (j % 2 == 0) {
                    List<MapBean.SubAreasbean.Pointsbean> pointsList = subArea.getPoints();
                    Path path = new Path();
                    boolean isFirstPoint = true;

                    for (MapBean.SubAreasbean.Pointsbean point : pointsList) {
                        float x = point.getX() - minXYList.get(0);
                        float y = point.getY() - minXYList.get(1);

//                        float x = point.getX() - 1200;
//                        float y = point.getY() - 1500;
                        // 对于第一个点，使用 moveTo()，对于其他点，使用 lineTo()
                        if (isFirstPoint) {
                            path.moveTo(x, y);
                            isFirstPoint = false;
                        } else {
                            path.lineTo(x, y);
                        }
                    }

                    // 将路径添加到列表并关闭路径
                    paths.add(path);
                    path.close(); // 确保路径被关闭
                }
            }
        }

        //加载小车
        for (CarBean bean : carBeans) {
            points.add(new PointF(bean.getX()- minXYList.get(0), bean.getY()- minXYList.get(1)));

            if(bean.getX()- minXYList.get(0) == 40.88733f){
                pivotX = bean.getX()- minXYList.get(0);
                pivotY = bean.getY()- minXYList.get(1);
            }


            if(bean.getX()- minXYList.get(0) == 10.171143f){
                pivotX = bean.getX()- minXYList.get(0);
                pivotY = bean.getY()- minXYList.get(1);
            }

            if(bean.getX()- minXYList.get(0) == -1.5894775f){
                pivotX = bean.getX()- minXYList.get(0);
                pivotY = bean.getY()- minXYList.get(1);
            }

            if(bean.getX()- minXYList.get(0) == 47.258057f){
                pivotX = bean.getX()- minXYList.get(0);
                pivotY = bean.getY()- minXYList.get(1);
            }
            if(bean.getX()- minXYList.get(0) == 45.127075f){
                pivotX = bean.getX()- minXYList.get(0);
                pivotY = bean.getY()- minXYList.get(1);
            }

//            Log.e("TagBBAN","deltaX1："+(bean.getX()- minXYList.get(0))+"   deltaY1:"+(bean.getY()- minXYList.get(1)));
        }
        invalidate(); // 重新绘制视图
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //计算放大后的地图边界
        RectF mapBounds = calculateScaledMapBounds(paths, scaleFactor);
        // 获取View的宽和高
        float viewWidth = getWidth();
        float viewHeight = getHeight();
        // 计算地图中心
        float mapCenterX = mapBounds.centerX();
        float mapCenterY = mapBounds.centerY();
        // 计算View中心
        float viewCenterX = viewWidth / 2f;
        float viewCenterY = viewHeight / 2f;
       // 计算偏移量，将地图中心移动到View中心
        float offsetX = viewCenterX - mapCenterX;
        float offsetY = viewCenterY - mapCenterY;

//      canvas.translate(offsetX,offsetY);

        // 计算该点放大后的新位置
        float scaledPivotX = pivotX * scaleFactor*scaleFactorCar;
        float scaledPivotY = pivotY * scaleFactor*scaleFactorCar;

        // 计算偏移量，以将放大后的点移动到View的中心
        float offsetX1 = viewCenterX - scaledPivotX;
        float offsetY1 = viewCenterY - scaledPivotY;
        Log.e("TagBBAN","deltaX："+viewWidth+"   deltaY:"+viewHeight);
        Log.e("TagBBAN","scaledPivotX："+scaledPivotX+"   scaledPivotY:"+scaledPivotY);
        // 绘制地图
        if (paths != null && colorList != null && colorList.size() >= paths.size()) {
            matrix.reset();
            // 如果pivotX和pivotY不为0，意味着我们有一个放大中心点
            if (pivotX != 0 && pivotY != 0) {
                // 应用缩放和平移
                matrix.reset();
                matrix.postScale(scaleFactor*scaleFactorCar, scaleFactor*scaleFactorCar); // 放大两倍
                matrix.postTranslate(offsetX1, offsetY1); // 平移

            } else {

                matrix.postScale(scaleFactor, scaleFactor);
                // 如果没有指定中心点，则默认以(0,0)为中心放大
//                matrix.postTranslate(translateX, translateY);
                matrix.postTranslate(offsetX, offsetY);
            }

                canvas.save();
                canvas.concat(matrix);
                paint.setStyle(Paint.Style.FILL_AND_STROKE);

                int colorNum = 0;
                for (Path path : paths) {
                    if (colorNum < colorList.size()) {
                        int color = Color.parseColor(colorList.get(colorNum));
                        paint.setColor(color);
                        paint.setStyle(Paint.Style.FILL);
                        canvas.drawPath(path, paint);
                        colorNum++;
                    }
                }
                canvas.restore();
            }

            //绘制小车
            if (points.size() >= 2) {

                matrix.reset();
                // 如果pivotX和pivotY不为0，意味着我们有一个放大中心点
                if (pivotX != 0 && pivotY != 0) {
                    // 应用缩放和平移
                    matrix.reset();
                    matrix.postScale(scaleFactor * scaleFactorCar, scaleFactor * scaleFactorCar); // 放大两倍
                    matrix.postTranslate(offsetX1, offsetY1); // 平移
                } else {
                matrix.postScale(scaleFactor, scaleFactor);
                 // 如果没有指定中心点，则默认以(0,0)为中心放大
//                matrix.postTranslate(translateX, translateY);
                    matrix.postTranslate(offsetX, offsetY);
            }


            canvas.save();
            canvas.concat(matrix);

            // 设置画笔为小车的样式
            Paint carPaint = new Paint();
            carPaint.setColor(Color.BLACK); // 设置小车颜色
            carPaint.setStrokeWidth(0); // 设置画笔宽度
            carPaint.setStyle(Paint.Style.FILL_AND_STROKE); // 线条模式

            for (int i = 0; i < 23; i++) {
                PointF startPoint = points.get(i);
                PointF endPoint = points.get(i + 1);
                canvas.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y, carPaint);
            }

            // 如果有至少24个点，连接第24个点和第一个点
            if (points.size() > 23) {
                PointF firstPoint = points.get(0);
                PointF lastPoint = points.get(23);
                canvas.drawLine(firstPoint.x, firstPoint.y, lastPoint.x, lastPoint.y, carPaint);
            }
            canvas.restore();
        }
    }


    /**
     * 小车实体  点的内部类，用于存储坐标
      */
    private class PointF {
        float x;
        float y;

        PointF(float x, float y) {
            this.x = x;
            this.y = y;
        }
    }

    // 计算放大后的地图边界
    private RectF calculateScaledMapBounds(List<Path> paths, float scaleFactor) {
        RectF bounds = new RectF();
        RectF pathBounds = new RectF();
        for (Path path : paths) {
            path.computeBounds(pathBounds, true);
            bounds.union(pathBounds);
        }
        bounds.left *= scaleFactor;
        bounds.top *= scaleFactor;
        bounds.right *= scaleFactor;
        bounds.bottom *= scaleFactor;
        return bounds;
    }
}
